package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.MiddleMapper;
import com.zhentao.mapper.RoleMapper;
import com.zhentao.mapper.UsersMapper;
import com.zhentao.pojo.Middle;
import com.zhentao.pojo.Users;
import com.zhentao.service.FileService;
import com.zhentao.service.UsersService;
import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author ls
* @description 针对表【users(用户基本信息表)】的数据库操作Service实现
* @createDate 2025-07-03 10:07:08
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService{

    @Resource
    UsersMapper usersMapper;
    @Resource
    MiddleMapper middleMapper;
    @Resource
    RoleMapper roleMapper;

    @Autowired
    FileService fileStorageService;


    @Override
    public Result listUsersByPage(Integer page, Integer size, String username) {
        // 创建分页对象
        Page<Users> pageParam = new Page<>(page, size);

        // 构建查询条件
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            wrapper.like("username", username);
        }
        wrapper.orderByDesc("user_id");

        // 执行分页查询
        Page<Users> userPage = this.page(pageParam, wrapper);

        // 返回分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("users", userPage.getRecords());
        result.put("total", userPage.getTotal());
        result.put("pages", userPage.getPages());
        result.put("current", userPage.getCurrent());
        result.put("size", userPage.getSize());

        return Result.OK(result);
    }

    @Override
    public Result addUser(Users user) {
        // 检查用户名是否已存在
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        if (this.count(wrapper) > 0) {
            return Result.ERROR("用户名已存在");
        }

        if (this.save(user)) {
            return Result.OK("用户添加成功");
        }
        return Result.ERROR("用户添加失败");

    }

    @Override
    public Result updateUser(Users user) {
        if (this.updateById(user)) {
            return Result.OK("用户更新成功");
        }
        return Result.ERROR("用户更新失败");

    }

    @Override
    @Transactional
    public Result deleteUser(Integer userId) {
        // 删除用户
        if (this.removeById(userId)) {
            // 删除用户角色关联
            QueryWrapper<Middle> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            middleMapper.delete(wrapper);
            return Result.OK("用户删除成功");
        }
        return Result.ERROR("用户删除失败");
    }

    @Override
    public Result getUserRoles(Integer userId) {
        // 查询用户的所有角色ID
        QueryWrapper<Middle> wrapper = new QueryWrapper<>();
        wrapper.select("role_id").eq("user_id", userId);
        List<Object> roleIds = middleMapper.selectObjs(wrapper);

        // 转换为整数列表
        List<Integer> ids = roleIds.stream()
                .map(id -> (Integer) id)
                .collect(Collectors.toList());

        return Result.OK(ids);
    }

    @Override
    @Transactional
    public Result saveUserRoles(Integer userId, List<Integer> roleIds) {
        // 删除现有角色
        QueryWrapper<Middle> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        middleMapper.delete(wrapper);

        // 添加新角色
        if (roleIds != null && !roleIds.isEmpty()) {
            List<Middle> relations = roleIds.stream()
                    .map(roleId -> {
                        Middle relation = new Middle();
                        relation.setUserId(userId);
                        relation.setRoleId(roleId);
                        return relation;
                    })
                    .collect(Collectors.toList());

            // 批量插入
            for (Middle relation : relations) {
                middleMapper.insert(relation);
            }
        }
        return Result.OK("角色分配成功");

    }

//    @Override
//    public void updateUserAvatar(Integer userId, String avatarUrl) {
//        // 删除旧头像
//        String oldAvatar = getUserAvatar(userId);
//        if (oldAvatar != null) {
//            fileStorageService.deleteAvatar(oldAvatar);
//        }
//
//        // 更新新头像
//        Users user = new Users();
//        user.setUserId(userId);
//        user.setAvatar(avatarUrl);
//        this.updateById(user);
//    }
//
//    @Override
//    public String getUserAvatar(Integer userId) {
//        Users user = this.getById(userId);
//        return user != null ? user.getAvatar() : null;
//    }
}




